package com.jn.algorithm.day018.question53;

import java.util.Arrays;

/**
 * @author 江南大学1033190417
 * @date 2022/5/9 20:33
 */
public class Solution {

    //滑动窗口
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {//i代表窗口大小
            for (int j = 0; j < n - i; j++) {//窗口移动次数
                //计算窗口内的和
                int he = 0;
                for (int k = j; k <= i + j; k++) {
                    he += nums[k];
                }
                if (he > max) {
                    max = he;
                }
            }
        }
        return max;
    }

    //贪心
    /*
       遍历一次数组，若当前<=0，则把当前和置为0，若当前和大于最大值，则更新最大值
     */
    public int maxSubArray2(int[] nums) {
        int n = nums.length;
        int maxRes = nums[0];
        int currentRes = 0;
        for (int i = 0; i < n; i++) {
            currentRes = Math.max(nums[i], currentRes + nums[i]);
            maxRes = Math.max(currentRes, maxRes);
        }
        return maxRes;
    }

    //动态规划
    /*
       若前一个值大于0，则加到当前值上
     */
    public int maxSubArray3(int[] nums) {
        int n = nums.length;
        for (int i = 1; i < n; i++) {
            if (nums[i-1]>0){
                nums[i]+=nums[i-1];
            }
        }
        int max=Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            if (nums[i]>max)
                max=nums[i];
        }
        return max;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(solution.maxSubArray2(nums));
    }
}
